package com.wehealth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.wehealth.dm.User;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Feedback extends Fragment {

	private EditText server_context;
	private User user;
	private MainActivity activity;
	private static  String JSONResult;
	private ProgressBar mProgress;
	private AlertDialog dialog;
	private View mView;

	public  Feedback()
	{
		Log.i("init:", "Feedback"); 
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		mView =  inflater.inflate(R.layout.feedback, null);
		return mView;
	
	}
	
	public void onActivityCreated(Bundle savedInstanceState){
		
		super.onActivityCreated(savedInstanceState);
		
		 activity = (MainActivity)getActivity();
		 user = activity.getUserInfo();
		 server_context = (EditText)activity.findViewById(R.id.online_server_et);
		 mProgress =(ProgressBar)activity.findViewById(R.id.progress);
		 
		 Button bBack = (Button) activity.findViewById(R.id.bBack_Feedback);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{
					
                    MainActivity activity = (MainActivity) getActivity();                       
                    activity.switchContentHome(); 
				}
			});
		 
		 ImageView  submit = (ImageView)activity.findViewById(R.id.submit_img);
		 submit.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String reply = server_context.getText().toString().trim();
				Log.i("SIMMON","reply= "+reply);
				if(reply==null||reply.equals("")){
					String resultStr = getString(R.string.online_server_noerror);
					openDialog("0",resultStr,"确定"); 
				}else{
				connectServierSubmitData();
				}
			}
		});
		 
		 
	}
	
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message paramMessage) {
			super.handleMessage(paramMessage);
			mProgress.setVisibility(View.GONE);
			if(JSONResult!=null){
				switch (paramMessage.what) {
				case 0:
					
					GetResult(JSONResult);
					break;
				}
				JSONResult =null;
			}else{
			  //  activity.openMainActivityDialog(); 
			}
		}
	};
	
	
	private void connectServierSubmitData(){
		mProgress.setVisibility(View.VISIBLE);
		new Thread(){
			@Override
			public void run(){
				try {
					getPlanData();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			Message msg = new Message();
			msg.what =0;
			handler.sendMessage(msg);
			}
		}.start();
	}
	
	private void  getPlanData() throws IOException
	{
		Log.d("SIMMON","user="+user);
		String userID =String.valueOf(user.getUserId());
		String message = server_context.getText().toString().trim();

		String httpUrl = com.wehealth.util.GetUrl.Feedback_Add_URL();
		 HttpPost httpRequest= new HttpPost(httpUrl);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 
		 params.add(new BasicNameValuePair("userID",userID));
		 params.add(new BasicNameValuePair("message",message)); 
		 try
		 {
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
				 Log.d("SIMMON","JSONResult ="+JSONResult);
			 }
		 }
		 catch(Exception e)
		 {
			
			 Log.e("error:",  e.toString());
			 
		 }

	}
	
	
	   private void GetResult(String strJSON){
	       try{
	
	                JSONObject jsonObject = new JSONObject(strJSON); 
	                String  result =   jsonObject.getString("result");
	               if(result.equals("1")){
	            	   String resultStr = getString(R.string.question_reply_add_sucess);
	            	   openDialog(result,resultStr,"确定"); 
	            	  
	               }else{
	            	   activity.openDialogBt(-100); 
	               }
	            }
	            catch(JSONException ex)
	            {
	                    Log.e("JSON Error: ", ex.toString()); 
	            }
	    }
	
	   
	    public void openDialog(final String result,String resultStr,String button){
	        final AlertDialog.Builder builder = new AlertDialog.Builder(activity); 
	        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_self_viewbt,null);
	        TextView textview = (TextView)view.findViewById(R.id.dialog_self_tx);
	        textview.setText(resultStr);
	        Button okBt =(Button)view.findViewById(R.id.dialog_self_bt);
	        okBt.setText(button);
	        okBt.setOnClickListener(new OnClickListener() {
	           
	           @Override
	           public void onClick(View arg0) {
	               // TODO Auto-generated method stub
                   InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);  
                   server_context.setCursorVisible(false);//失去光标
                   imm.hideSoftInputFromWindow(mView.getWindowToken(), 0);
                   if(result.equals("1")){
                	   activity.switchContentHome();
                   }
	               dialog.cancel();
	           }
	       });
	        builder.setView(view);
	        dialog=  builder.create();
	        dialog.show();
	    }
	
	
}
